package com.wkh.project.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wkh.project.common.result.ResultCodeEnum;
import com.wkh.project.common.util.IpUtil;
import com.wkh.project.customer.config.WxConfigOperator;
import com.wkh.project.customer.mapper.CustomerInfoMapper;
import com.wkh.project.customer.mapper.CustomerLoginLogMapper;
import com.wkh.project.customer.service.CustomerInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wkh.project.customer.service.CustomerInfoService;
import com.wkh.project.model.entity.customer.CustomerInfo;
import com.wkh.project.model.entity.customer.CustomerLoginLog;
import com.wkh.project.model.form.customer.UpdateCustomerInfoForm;
import com.wkh.project.model.form.customer.UpdateWxPhoneForm;
import com.wkh.project.model.vo.customer.CustomerLoginVo;
import com.wkh.project.service.execption.GuiguException;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Resource
    private WxMaService wxMaService;
    @Resource
    private CustomerLoginLogMapper customerLoginLogMapper;
    @Override
    public Long login(String code) {
        String openid = null;
        //1.根据code调用微信工具包对象，获取微信唯一标识openId
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openid = sessionInfo.getOpenid();
        } catch (WxErrorException e) {
            throw new GuiguException(ResultCodeEnum.WX_CODE_ERROR);
        }
        //2.根据openId查询数据库表，判断是否为第一次登录
        LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerInfo::getWxOpenId,openid);
        CustomerInfo customerInfo = this.getOne(queryWrapper);
        //3.如果为第一次登录，则进行注册逻辑，添加信息到用户表
        if (customerInfo == null){
            customerInfo = new CustomerInfo();
            customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            customerInfo.setWxOpenId(openid);
            customerInfo.setNickname(StrUtil.uuid());
            boolean save = this.save(customerInfo);
        }
        //4.记录登录日志信息
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();
        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("小程序登录");
        int insert = customerLoginLogMapper.insert(customerLoginLog);
        //5.返回用户id

        return customerInfo.getId();
    }

    @Override
    public CustomerLoginVo getCustomerLoginInfo(Long customerId) {
        //1.根据id查询数据库中的值
        CustomerInfo customerInfo = this.getById(customerId);
        //2.拷贝数据到CustomerLoginVo中
        CustomerLoginVo customerLoginVo = new CustomerLoginVo();
        BeanUtil.copyProperties(customerInfo,customerLoginVo);
        boolean isBindPhone = StrUtil.isBlank(customerInfo.getPhone());
        log.info("isBindPhone为：{}",isBindPhone);
        customerLoginVo.setIsBindPhone(!isBindPhone);
        //3.返回数据
        return customerLoginVo;
    }

    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        //1 根据code值获取微信绑定手机号码
        try {
            WxMaPhoneNumberInfo phoneNoInfo =
                    wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
            String phoneNumber = phoneNoInfo.getPhoneNumber();

            //更新用户信息
            Long customerId = updateWxPhoneForm.getCustomerId();
            CustomerInfo customerInfo = this.getById(customerId);
            customerInfo.setPhone(phoneNumber);
            this.updateById(customerInfo);
            return true;
        } catch (WxErrorException e) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    public Boolean updateCustomerInfo(UpdateCustomerInfoForm updateCustomerInfoForm) {
        CustomerInfo customerInfo = new CustomerInfo();
        BeanUtil.copyProperties(updateCustomerInfoForm,customerInfo);
        customerInfo.setId(updateCustomerInfoForm.getCustomerId());
        boolean updated = this.updateById(customerInfo);
        return true;
    }

    @Override
    public String getCustomerOpenId(Long customerId) {
        CustomerInfo customerInfo = this.getOne(new LambdaQueryWrapper<CustomerInfo>().eq(CustomerInfo::getId, customerId).select(CustomerInfo::getWxOpenId));
        return customerInfo.getWxOpenId();
    }
}
